<template>
	<view class="poster">
		<image src="https://master.shengejiaju.cn/web/static/images/pic_banner@2x.png" class="poster-banner"></image>
		<view class="poster-hd">
			<canvas canvas-id="CanvasID" :style="{ width: canvasW + 'px', height: canvasH + 'px' }" @click="custom"></canvas>
		</view>
		<view class="poster-btn">
			<button class="share" @click="share">分享</button>
			<button type="primary" class="custom" @click="submit">保存</button>
			<button plain type="primary" class="rest" @click="rest">重置</button>
		</view>
		
		<uni-popup ref="sharePop" type="bottom">
			<view class="share-pop">
				<!-- #ifdef APP-PLUS -->
				<view class="share-pop-tit">分享到：</view>
				<!-- #endif -->
				<view class="share-pop-list">
					<!-- #ifdef APP-PLUS -->
					<view class="share-pop-list-item" @click="shareBtn(1)"><image src="../../static/share/icon_weixin.png"></image><text>微信好友</text></view>
					<view class="share-pop-list-item" @click="shareBtn(2)"><image src="../../static/share/icon_pengyouquan.png"></image><text>朋友圈</text></view>
					<!-- <view class="share-pop-list-item" @click="shareBtn(3)"><image src="../../../static/share/icon_weibo.png"></image><text>新浪微博</text></view> -->
					<!-- #endif -->
				</view>
				<view class="share-save"><button plain type="primary" @click="save">保存海报到相册 <!-- #ifdef MP-WEIXIN -->后即可分享<!-- #endif --></button></view>
			</view>
		</uni-popup>
		
	</view>
</template>

<script>
	const md5 = require('../../static/utils/md5')
	import host from '@/api/config.js'
	export default {
		data() {
			return {
				imgSrc: 'https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/images/mroes_middle_img/2020-05-27/new15905760111016.jpg',
				QrSrc: '',
				canvasW: 0,
				canvasH: 0,
				canvasImgSrc:'',
				ctx: null,
				Title: '家具大师',
				Referrer: '',
				ViewDetails: '扫码/长按识别二维码',
				uploadParameter: {}
			};
		},
		onLoad(options) {
			this.init()
			this.getUserInfo()
		},
		methods: {
			// 参数排序
			objKeySort(obj) {
				var newkey = Object.keys(obj).sort();
				var newObj = {};
				for (var i = 0; i < newkey.length; i++) {
						newObj[newkey[i]] = obj[newkey[i]];
				}
				return newObj;
			},
			init(){
				let data = {}
				// #ifdef H5
				let ua = navigator.userAgent.toLowerCase()
				if (ua.match(/MicroMessenger/i) == "micromessenger") {
					data.port = 'wechat'
				}else{
					data.port = 'h5'
				}
				// #endif
				
				// #ifdef APP-PLUS
				switch(uni.getSystemInfoSync().platform){
					case 'android':
						data.port = 'android'
					  break;
					case 'ios':
						data.port = 'ios'
					  break;
				}
				// #endif
				
				data.key = JSON.parse(uni.getStorageSync('userInfo')).token
				
				data.timestamp = Math.round(new Date() * 1000)
				// 获取签名开始
				let obj = 'jjds2020+'
				let newObj = this.objKeySort(data)
				for (let i in newObj){
					obj += i + '=' + newObj[i] +'&'
				}
				obj = obj.substring(0, obj.length - 1)
				obj += '+jjds2020'
				obj = md5.hexMD5(obj)
				obj = obj.toUpperCase()
				// 获取签名结束
				data.sign = obj
				this.uploadParameter = data
				this.$api.CaseClassJson().then(res => {
					this.classList = res.datas
				})
				this.$api.CaseSpaceJson().then(res => {
					this.spaceList = res.datas
				})
			},
			getUserInfo(){
				this.$api.UserInfo().then(res => {
					this.Title = res.datas.nickname
					this.Referrer = res.datas.phone
				}).then(res => {
					this.$api.GetQRcode().then(qrRes => {
						this.QrSrc = qrRes.datas
					}).then(qrRes => {
						this.OnCanvas();
					})
				})
			},
			async OnCanvas() {
				let _this = this;
				_this.ctx = uni.createCanvasContext('CanvasID');
				const systemInfo = uni.getSystemInfoSync()
				const _imgInfo = await _this.getImageInfo({ imgSrc: _this.imgSrc }); // 背景图
				const _QrCode = await _this.getImageInfo({ imgSrc: _this.QrSrc }); //二维码
				_this.canvasW = uni.upx2px(540);
				_this.canvasH = uni.upx2px(800);
				
				_this.ctx.setFillStyle('#FFFFFF');
				_this.ctx.fillRect(0,0,_this.canvasW,_this.canvasH)
				
				//添加图片展示
				_this.ctx.drawImage(_imgInfo.path, 0, 0, _this.canvasW, uni.upx2px(570));
				//添加图片展示 end
				
				let top = uni.upx2px(30),
						left = uni.upx2px(350);
				
				if(systemInfo.platform==='ios'){
					top = uni.upx2px(20)
				}
				
				//添加二维码
				_this.ctx.drawImage(_QrCode.path, left,uni.upx2px(580) + top, uni.upx2px(160), uni.upx2px(160));
				//添加二维码 end
				
				_this.ctx.setFontSize(uni.upx2px(34));
				_this.ctx.setFillStyle('#333');
				if(_this.Title.length > 9){
					_this.ctx.fillText(_this.Title.substring(0,8) + '..', 15,uni.upx2px(590) + top + 20);
				}else{
					_this.ctx.fillText(_this.Title, 15,uni.upx2px(590) + top + 20);
				}
				
				_this.ctx.setFontSize(uni.upx2px(28));
				_this.ctx.setFillStyle('#666');
				_this.ctx.fillText(_this.Referrer, 15,uni.upx2px(590) + top + 40);
				
				_this.ctx.setFontSize(uni.upx2px(22));
				_this.ctx.setFillStyle('#999');
				_this.ctx.fillText(_this.ViewDetails, 15, uni.upx2px(590) + top + 70);
				
				//延迟后渲染至canvas上
				setTimeout(function() {
					_this.ctx.draw();
				}, 600);
			},
			async getImageInfo({ imgSrc }) {
				uni.showLoading({
					title: '正在生成海报',
					mask: true
				})
				return new Promise((resolve, errs) => {
					if(imgSrc.indexOf('https')!=-1){
						uni.downloadFile({
							url: imgSrc,
							success:function(res){
								uni.getImageInfo({
									src: res.tempFilePath,
									success: function(image) {
										uni.hideLoading()
										resolve(image);
									},
									fail(err) {
										uni.hideLoading()
										uni.showToast({
											title: '生成失败，请退出重试',
											icon: 'none',
											duration: 1500
										})
										errs(err);
									}
								});
							}
						})
					}else{
						uni.getImageInfo({
							src: imgSrc,
							success: function(image) {
								uni.hideLoading()
								resolve(image);
							},
							fail(err) {
								uni.hideLoading()
								uni.showToast({
									title: '生成失败，请退出重试',
									icon: 'none',
									duration: 1500
								})
								errs(err);
							}
						});
					}
				});
			},
			// 自定义选择图片
			custom(){
				let _this = this
				uni.chooseImage({
					count: 1,
					sourceType: ['album','camera'],
					success(res) {
						let imgs = []
						res.tempFiles.forEach(item => {
							imgs.push({
								uri: item.path
							})
						})
						uni.showLoading({
							title: '正在上传···',
							mask: true
						})
						uni.uploadFile({
							url: `${host}/api/Upimg/Upimg`,
							filePath: imgs[0].uri,
							name: 'file',
							formData: {
								port: _this.uploadParameter.port,
								key: _this.uploadParameter.key,
								timestamp: _this.uploadParameter.timestamp,
								sign: _this.uploadParameter.sign
							},
							success: (uploadFileRes) => {
								_this.imgSrc = JSON.parse(uploadFileRes.data).datas[0]
								_this.OnCanvas();
							},
							complete: () => {
								uni.hideLoading()
							}
						});
					}
				})
			},
			// 重置
			rest(){
				this.imgSrc = 'https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/images/mroes_middle_img/2020-05-27/new15905760111016.jpg'
				this.OnCanvas();
			},
			// 保存图片到相册
			saveImg(){
				uni.showModal({
					content: '保存海报后即可从相册分享或发送给朋友，是否保存?',
					confirmText: '是',
					cancelText: '否',
					success(res) {
						if(res.confirm){
							uni.showLoading({
								title: '正在保存',
								mask: true
							})
							uni.canvasToTempFilePath({
							  destWidth: 600,
							  destHeight: 1070,
							  canvasId: 'CanvasID',
							  success: function(data) {
									uni.hideLoading()
									uni.saveImageToPhotosAlbum({
										filePath: data.tempFilePath,
										success(saveRes) {
											uni.showToast({
												icon: 'none',
												title: '保存成功，请在相册中查看',
												duration: 1500
											})
										},
										fail(fail) {
											uni.hideLoading()
										}
									})
							  }
							})
						}
					}
				})
			},
			// 分享保存
			save(){
				this.saveImg()
			},
			// 分享操作
			share(){
				let _this = this
				
				// #ifdef H5
				this.saveImg()
				return false
				// #endif
				
				// #ifdef APP-PLUS  || MP-WEIXIN
				this.$refs.sharePop.open()
				// #endif

			},
			// 点击分享
			shareBtn(e){
				if(e!=3){
					let scene = ''
					if(e==1){
						scene = 'WXSceneSession'
					}else if(e==2){
						scene = 'WXSenceTimeline'
					}
					let img = '';
					uni.showLoading({
						title: '正在生成··',
						mask: true
					})
					uni.canvasToTempFilePath({
					  destWidth: 600,
					  destHeight: 1070,
					  canvasId: 'CanvasID',
					  success: function(data) {
							uni.hideLoading()
							img = data.tempFilePath
							uni.share({
								provider: "weixin",
								scene: scene,
								type: 2,
								imageUrl: img,
								success: function (res) {
									console.log("success:" + JSON.stringify(res));
								},
								fail: function (err) {
									console.log("fail:" + JSON.stringify(err));
								}
							});
					  }
					})
				}else{
					let img = '';
					uni.showLoading({
						title: '正在生成··',
						mask: true
					})
					uni.canvasToTempFilePath({
					  destWidth: 600,
					  destHeight: 1070,
					  canvasId: 'CanvasID',
					  success: function(data) {
							uni.hideLoading()
							img = data.tempFilePath
							uni.share({
								provider: 'sinaweibo',
								type: 2,
								imageUrl: img,
								success: function (res) {
									console.log("success:" + JSON.stringify(res));
								},
								fail: function (err) {
									console.log("fail:" + JSON.stringify(err));
								}
							});
					  }
					})
				}
			},
			submit(){
				if(this.imgSrc == 'https://jiajudashi.oss-cn-shenzhen.aliyuncs.com/images/mroes_middle_img/2020-05-27/new15905760111016.jpg'){
					uni.showToast({
						icon: 'none',
						title: '请先上传您的图文海报!'
					})
					return false
				}
				this.$api.PosterAdd({store_id: JSON.parse(uni.getStorageSync('userInfo')).store_id,image: this.imgSrc}).then(res => {
					uni.showToast({
						icon: 'none',
						title: '保存成功!'
					})
					setTimeout(() => {
						uni.navigateBack()
					},1500)
				})
			},
		},
		mounted() {
			
		}
	}
</script>

<style lang="scss">
	.poster{
		padding-top: 280rpx;
		padding-bottom: 130rpx;
		.poster-banner{
			position: absolute;
			left: 0;
			top: 0;
			width: 100%;
			height: 370rpx;
		}
		canvas{
			background-color: #FFF;
			display: block;
			margin: 0 auto;
			box-shadow: 0px 8rpx 16rpx 0px rgba(0, 0, 0, 0.24);
		}
		.poster-btn{
			position: fixed;
			height: 110rpx;
			bottom: 0;
			left: 0;
			right: 0;
			background-color: #FFF;
			display: flex;
			justify-content: center;
			align-items: center;
			button{
				height: 60rpx;
				line-height: 60rpx;
				border-radius: 10rpx;
				font-size: 28rpx;
				width: 170rpx;
				margin: 0 20rpx;
				&.share{
					background-color: #FE9B26;
					color: #FFF;
				}
			}
		}
		.share-pop{
			background-color: #FFF;
			padding: 40rpx 0;
			.share-pop-tit{
				text-align: center;
				margin-bottom: 40rpx;
			}
			.share-pop-list{
				display: flex;
				.share-pop-list-item{
					flex: 1;
					text-align: center;
					image{
						width: 80rpx;
						height: 80rpx;
						vertical-align: top;
					}
					text{
						font-size: 24rpx;
						display: block;
						margin-top: 20rpx;
					}
				}
			}
			.share-save{
				margin-top: 40rpx;
				padding: 0 80rpx;
				button{
					border-radius: 100rpx;
					height: 80rpx;
					line-height: 80rpx;
				}
			}
		}
	}
</style>